package org.example.ipsAppServer;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.AudioProcessor;
import org.example.data.PositionDataDetail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;


public class IpsStart
{
//    ips的udp接口
    private static final int PORT = 2323;
    private static final int BUFFER_SIZE = 1024;
    private static final Logger logger = LoggerFactory.getLogger(IpsStart.class);

//    音频处理器
    private AudioProcessor audioProcessor;
//    ips服务
    private DatagramSocket socket = null;
//    ips的运行入口
    public void run(){

        while(true)
        {
            try {

                serverStart();
            } catch (Exception e) {
                close();
                logger.error("未知异常，5秒后重启系统正在重启服务",e);
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException ex) {
                    throw new RuntimeException(ex);
                }
            }
        }
    }

    private void serverStart() throws Exception {
//        对音频处理器进行实例
            audioProcessor = new AudioProcessor("192.168.20.126", 1702);
//

        try {
            socket = new DatagramSocket(PORT);
        } catch (SocketException e) {
            throw new Exception(PORT+":udp端口创建失败",e);
        }
        logger.info("UDP服务器启动，监听端口: " + PORT);
        byte[] buffer = new byte[BUFFER_SIZE];

        while(true)
        {
            // 接收数据包
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
            try {
                socket.receive(packet);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            // 处理接收到的数据
            String receivedData = new String(packet.getData(), 0, packet.getLength());

            ObjectMapper objectMapper = new ObjectMapper();
            PositionDataDetail positionData = null;
            try {
                positionData = objectMapper.readValue(receivedData, PositionDataDetail.class);
            } catch (Exception e) {

                e.printStackTrace();
            }
            // 音频处理器命令
            audioProcessor.autoSendProcessor(positionData);
            logger.info("positionData:"+positionData);



        }
    }

    public void close()
    {
        if(socket != null)
        {
            try {
                socket.close();
            } catch (Exception e) {
                e.printStackTrace();
                logger.info("socket 关闭失败");
            }
        }
        if(audioProcessor != null)
        {
            audioProcessor.close();
        }

    }

}
